import React from 'react';
import { View, Text, TouchableOpacity, StyleSheet, Alert } from 'react-native';
import { useTranslation } from '@/app/utils/useTranslation';
import { SupportedLanguage } from '@/app/utils/i18n';

interface LanguageSelectorProps {
  style?: any;
  showCurrentLanguage?: boolean;
}

export function LanguageSelector({ style, showCurrentLanguage = true }: LanguageSelectorProps) {
  const { currentLanguage, changeLanguage, supportedLanguages, t } = useTranslation();

  const handleLanguageChange = (language: SupportedLanguage) => {
    if (language === currentLanguage) return;

    Alert.alert(
      t('settings.changeLanguage'),
      t('settings.changeLanguageConfirm'),
      [
        {
          text: t('common.cancel'),
          style: 'cancel'
        },
        {
          text: t('common.confirm'),
          onPress: () => changeLanguage(language)
        }
      ]
    );
  };

  return (
    <View style={[styles.container, style]}>
      {showCurrentLanguage && (
        <Text style={styles.currentLanguageText}>
          {t('settings.currentLanguage')}: {supportedLanguages[currentLanguage].nativeName}
        </Text>
      )}
      
      <View style={styles.languageList}>
        {Object.entries(supportedLanguages).map(([code, info]) => (
          <TouchableOpacity
            key={code}
            style={[
              styles.languageItem,
              currentLanguage === code && styles.selectedLanguageItem
            ]}
            onPress={() => handleLanguageChange(code as SupportedLanguage)}
          >
            <Text style={[
              styles.languageText,
              currentLanguage === code && styles.selectedLanguageText
            ]}>
              {info.nativeName}
            </Text>
            <Text style={[
              styles.languageSubText,
              currentLanguage === code && styles.selectedLanguageSubText
            ]}>
              {info.name}
            </Text>
          </TouchableOpacity>
        ))}
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    padding: 16,
  },
  currentLanguageText: {
    fontSize: 16,
    fontWeight: '600',
    marginBottom: 16,
    color: '#333',
  },
  languageList: {
    gap: 8,
  },
  languageItem: {
    padding: 16,
    borderRadius: 8,
    borderWidth: 1,
    borderColor: '#e0e0e0',
    backgroundColor: '#f9f9f9',
  },
  selectedLanguageItem: {
    borderColor: '#007AFF',
    backgroundColor: '#E3F2FD',
  },
  languageText: {
    fontSize: 16,
    fontWeight: '500',
    color: '#333',
  },
  selectedLanguageText: {
    color: '#007AFF',
  },
  languageSubText: {
    fontSize: 14,
    color: '#666',
    marginTop: 2,
  },
  selectedLanguageSubText: {
    color: '#0056CC',
  },
});